package uk.co.hs.web.controller.admin;

import javax.servlet.http.HttpServletRequest;

import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.springframework.beans.propertyeditors.CustomBooleanEditor;
import org.springframework.beans.propertyeditors.CustomNumberEditor;
import org.springframework.beans.propertyeditors.StringTrimmerEditor;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.servlet.ModelAndView;

import uk.co.hs.constants.HsConstants;
import uk.co.hs.property.editors.ClassPropertyEditor;
import uk.co.hs.web.property.editor.JodaTimePropertyEditor;

/**
 * AdminEditController.
 */
public class AdminEditController
{
  protected final static DateTimeFormatter DATE_FORMATTER = DateTimeFormat.forPattern(HsConstants.SCREEN_DATE_FORMAT);
  /**
   * Redirects the page to admin. Error if an Exception occurs.
   *
   * @param aException Exception thrown.
   * @return ModelAndView for the admin.Error page.
   */
  @ExceptionHandler(Exception.class)
  protected ModelAndView handleException(Exception aException)
  {
    return new ModelAndView("hs_Error").addObject("exception", aException);
  }

  @InitBinder
  protected void initBinder(HttpServletRequest aRequest,
                            ServletRequestDataBinder aBinder) throws Exception
  {
    JodaTimePropertyEditor jodaDateEditor = new JodaTimePropertyEditor(DATE_FORMATTER);
    CustomBooleanEditor booleanEditor = new CustomBooleanEditor(false);
    aBinder.registerCustomEditor(DateTime.class, jodaDateEditor);
    aBinder.registerCustomEditor(String.class, new StringTrimmerEditor(true));
    aBinder.registerCustomEditor(Boolean.class, booleanEditor);
    aBinder.registerCustomEditor(Class.class, new ClassPropertyEditor());
    aBinder.registerCustomEditor(Integer.class, new CustomNumberEditor(Integer.class, true));
  }
}
